<?php

namespace App\Models;

use Throwable;
use Encore\Admin\Form;
use App\Support\Currency;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class YecRecord extends Model
{
    const TYPE_RECHARGE = 0; // 充值
    const TYPE_WITHDRAW = 1; // 提现

    const STATUS_UNCONFIRMED = 0;
    const STATUS_CONFIRMED   = 1;
    const STATUS_REJECT      = 2;
    const STATUS_QUOTA      = 3;
    const STATUS_QUOTA_EXAMINE = 4;
    const STATUS_ABNORMAL = 5;


    public static $statusMap = [
        self::STATUS_UNCONFIRMED => '未审核',
        self::STATUS_CONFIRMED   => '已审核',
        self::STATUS_REJECT      => '已驳回',
    ];
    public static $statusAbnormalMap = [
        self::STATUS_ABNORMAL => '状态异常',
    ];

    public static $statusQuotaMap = [
        self::STATUS_QUOTA      => '超过限额',
        self::STATUS_QUOTA_EXAMINE      => '待执行',
    ];

    public static $typeMap = [
        self::TYPE_RECHARGE => '充值',
        self::TYPE_WITHDRAW => '提现',
    ];

    protected $fillable = [
        'type',
        'value',
        'user_id',
        'status',
        'enable_value',
        'to_address_id',
        'from_address_id',
        'enable_yecs_value'
    ];

    use Notifiable {
        notify as protected laravelNotify;
    }

    public function notify($instance)
    {
        // 只有数据库类型通知才需提醒，Email 或者其他的都 Pass
        if (method_exists($instance, 'toDatabase')) {
            DB::table('admin_users')->increment('notification_count', 1);
        }

        $this->laravelNotify($instance);
    }

    /**
     * @param  Form  $form
     * @return bool
     * @throws Throwable
     */
    public function markAsRead(Form $form)
    {
        if ($form->model()->status != self::STATUS_UNCONFIRMED) {
            return false;
        }
        if ($form->status == self::STATUS_REJECT) {
            return true;
        }
        $model = $form->model();
        $func = function () use ($model) {
            $yec = [
                'currency' => Currency::YEC,
                'user_id' => $model->user_id,
                'value' => $model->enable_value
            ];

            if ($model->type == self::TYPE_RECHARGE) {
                $yecs = [
                    'user_id' => $model->user_id,
                    'currency' => Currency::YECS,
                    'value' => $model->enable_yecs_value
                ];
                $yecs['type'] = '充值';
                $yec['type'] = '充值';

                $model->records()->create($yecs);
            } else {
                $yec['type'] = '提币';
                $model->user->addFreezeByCurrency(Currency::ETH, $model->value);
            }

            $model->records()->create($yec);
        };

        try {
            DB::transaction($func);
        } catch (Throwable $exception) {
            Log::error("审核失败：{yec_records.id: {$form->id}}");
            throw $exception;
        }
        return true;
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function link($params)
    {
        return route('yecrecord.show', $params);
    }

    public function toAddress()
    {
        return $this->belongsTo(Address::class, 'to_address_id')->withTrashed();
    }

    public function fromAddress()
    {
        return $this->belongsTo(Address::class, 'from_address_id')->withTrashed();
    }

    public function records()
    {
        return $this->morphMany(Record::class, 'recordable');
    }
}
